//
//  SelectPictureViewController.swift
//  01-照片选择
//
//  Created by Apple on 15/9/29.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

/// 可重用标示符号
private let SelectPictureViewCellID = "SelectPictureViewCellID"
/// 最大选择照片数量
private let SelectPictureMaxCount = 9

class SelectPictureViewController: UICollectionViewController {

    /// 照片数组
    lazy var pictures = [UIImage]()
    /// 用户当前选中的照片索引
    private var currentIndex = 0
    
    // MARK: - 构造函数
    init() {
        let layout = UICollectionViewFlowLayout()
        // 越大的屏幕，同一屏幕应该提供更多的内容！不是完全的等比例放大
        layout.itemSize = CGSize(width: 80, height: 80)
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 0, right: 10)
        
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 提示：collectionViewController中，view != collectionView
        collectionView?.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        
        // Register cell classes
        self.collectionView!.registerClass(SelectPictureViewCell.self, forCellWithReuseIdentifier: SelectPictureViewCellID)
    }

    // MARK: UICollectionViewDataSource
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        // 数量要比照片数组多1，最后一个是添加按钮，但是如果到达上限，不再显示添加按钮
        return pictures.count + (pictures.count == SelectPictureMaxCount ? 0 : 1)
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(SelectPictureViewCellID, forIndexPath: indexPath) as! SelectPictureViewCell
    
        cell.pictureDelegate = self
        
        // 设置照片
        if indexPath.item == pictures.count {
            cell.image = nil
        } else {
            cell.image = pictures[indexPath.item]
        }
    
        return cell
    }
}

// MARK: - 实现 SelectPictureViewCellDelegate
extension SelectPictureViewController: SelectPictureViewCellDelegate {
    private func selectPictureViewCellDidAdd(cell: SelectPictureViewCell) {
        
        // 1. 判断是否能够访问相册
        if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) {
            print("无法访问相册")
            return
        }
        
        // 2. 记录用户选中照片
        let indexPath = collectionView!.indexPathForCell(cell)!
        currentIndex = indexPath.item
        
        // 3. 创建选择器
        let picker = UIImagePickerController()
        picker.delegate = self
        // 允许编辑 － 适用于上传头像之前的编辑操作，图像小，用户定制
        // picker.allowsEditing = true
        
        presentViewController(picker, animated: true, completion: nil)
    }
    
    private func selectPictureViewCellDidRemove(cell: SelectPictureViewCell) {
        print("删除照片")
        
        // 1. 获取要删除的照片索引
        let indexPath = collectionView!.indexPathForCell(cell)!
        
        // 2. 如果是添加按钮，直接返回
        if indexPath.item == pictures.count {
            return
        }
        
        // 3. 删除数据
        pictures.removeAtIndex(indexPath.item)
        
        // 4. 动画刷新控件
//        collectionView?.deleteItemsAtIndexPaths([indexPath])
        collectionView?.reloadData()
    }
}

// MARK: - 系统照片选择协议
extension SelectPictureViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        let scaleImage = image.scaleImage(300)
        
        print("当前选中索引 \(currentIndex)")
        
        // 如果 currentIndex == 照片数组计数，标示点击的是添加按钮
        if currentIndex == pictures.count {
            // 添加到照片数组
            pictures.append(scaleImage)
        } else {
            // 更新指定位置的照片
            pictures[currentIndex] = scaleImage
        }
        
        // 刷新数据
        collectionView?.reloadData()
        
        // 一旦实现了代理方法，要自己 dismiss
        dismissViewControllerAnimated(true, completion: nil)
    }
}

// MARK: - 照片选择 Cell 协议
private protocol SelectPictureViewCellDelegate: NSObjectProtocol {
    /// 添加照片
    func selectPictureViewCellDidAdd(cell: SelectPictureViewCell)
    /// 删除照片
    func selectPictureViewCellDidRemove(cell: SelectPictureViewCell)
}

// MARK: - 照片选择 Cell
private class SelectPictureViewCell: UICollectionViewCell {
    
    /// 照片
    var image: UIImage? {
        didSet {
            addButton.setImage(image ?? UIImage(named: "compose_pic_add"), forState: .Normal)
            addButton.setImage(image ?? UIImage(named: "compose_pic_add_highlighted"), forState: .Highlighted)
            
            // 如果有图像，就显示删除按钮
            removeButton.hidden = (image == nil)
        }
    }
    
    // 照片 cell 代理
    weak var pictureDelegate: SelectPictureViewCellDelegate?
    
    // MARK: - 按钮监听方法
    @objc private func addPicture() {
        pictureDelegate?.selectPictureViewCellDidAdd(self)
    }
    
    @objc private func removePicture() {
        pictureDelegate?.selectPictureViewCellDidRemove(self)
    }
    
    // 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        // 1. 添加控件
        contentView.addSubview(addButton)
        contentView.addSubview(removeButton)
        
        // 2. 自动布局
        addButton.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        removeButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView.snp_top)
            make.right.equalTo(contentView.snp_right)
        }
        
        // 3. 添加监听方法
        addButton.addTarget(self, action: "addPicture", forControlEvents: .TouchUpInside)
        removeButton.addTarget(self, action: "removePicture", forControlEvents: .TouchUpInside)
        
        // 4. 按钮不能直接修改填充模式
        addButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
    }
    
    // MARK: - 懒加载控件
    /// 添加按钮
    private lazy var addButton: UIButton = UIButton(imageName: "compose_pic_add", backImageName: nil)
    /// 删除按钮
    private lazy var removeButton: UIButton = UIButton(imageName: "compose_photo_close", backImageName: nil)
}
